package MyPack;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.util.Base64;
//import java.util.Base64;
import java.lang.Object;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 


import com.google.gson.JsonObject;
 
public class SaveSignature extends HttpServlet {
    
    private static final long serialVersionUID = 1L;
    private static final String DESTINATION_DIR_PATH ="/signatureFolder";
    private File destinationDir, filePath;
    
    public SaveSignature() {
        super();
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // nothing here
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //PrintWriter to send the JSON response back
        PrintWriter out = response.getWriter();
 
        //set content type and header attributes
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
        
        JsonObject myObj = new JsonObject();
        
        String signatureData = request.getParameter("signatureData");
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        String fileName = "Signature_" + getTodaysDate() + "_" + getCurrentTime() + ".png";
        
        destinationDir = new File(realPath);
        if(!destinationDir.isDirectory()) {
            myObj.addProperty("success", false);
            myObj.addProperty("message", "Signature destination folder not found!");
        }
        else {
            filePath = new File(realPath, fileName);
            
            Base64.decodeToFile(signatureData, filePath.getPath());
            myObj.addProperty("success", true);
            myObj.addProperty("fileName", fileName);
        }
        out.println(myObj.toString());
        out.close();
        
    }
    
    private String getTodaysDate() { 
 
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String todaysDate = dateFormat.format(System.currentTimeMillis());
        return todaysDate;
 
    }
 
    private String getCurrentTime() {
 
        DateFormat dateFormat = new SimpleDateFormat("kkmmss");
        String currentTime = dateFormat.format(System.currentTimeMillis());
        return currentTime;
 
    }
 
}

